<template>
  <div class="temp" ref="layout" v-show="showPage">
    <!-- 头部 -->
    <div
      :class="{'header':true,'header-solid':showHeaderColor ,'header-bg':showHeaderColor||currentScrollTop > 1}">
      <a class="iconfont icon-aleft back-left" @click.stop="back()"></a>
      <!-- 手机、QQ 档案 -->
      <div class="title" v-if="pageTag.type === '004'||pageTag.type === '005'">
        <ul :class="{'title-tel-box':true,'title-tel-box_qq':pageTag.type === '005'}">
          <li class="title-tel-text">{{title.text}}</li>
          <li>{{title.reg}}</li>
        </ul>
      </div>
      <!-- 其它 -->
      <div class="head-children_opacity" v-else-if="currentScrollTop > 5">
        <img :src="headerImageUrl" class="top-img head-children_opacity">
      </div>

      <!-- 导航冻结栏 -->
      <mt-navbar class="nav-bar head-children_opacity" v-model="selectNavTop"
                 v-if="list.length > 0 && currentScrollTop > 1">
        <mt-tab-item class="nav-bar-item"
                     v-for="(item,index) in list"
                     :id="item.top"
                     :key="index">
          <span :class="{'nav-text':true,'iconfont icon-lct':selectNav === index}">{{item.text}}</span>
        </mt-tab-item>
      </mt-navbar>
    </div>

    <!-- 内容 -->
    <div :class="{'layout-body':true,'layout-body_top':pageTag.type === '004'||pageTag.type === '005'}"
         v-infinite-scroll="loadMore"
         infinite-scroll-disabled="loading"
         infinite-scroll-distance="10"
         ref="layoutBody">
      <slot></slot>
    </div>
    <!-- 底部 -->
    <footer>
      <div class="button other" v-if="controlShow" @click.stop="controlAction()">布控
      </div>
      <div class="button" v-if="!myAttention" @click.stop="attentionAction">关注</div>
      <div class="button cancel" v-else-if="myAttention" @click.stop="attentionAction">取消关注</div>
    </footer>
  </div>
</template>

<script>
  import {scrollTop} from '../helper/animation'
  import {ANDROID} from '../config'
  import request from '../helper/request'

  /**
   * 档案页面布局
   * @module src/components/lay-out.vue
   *
   * props
   * @member
   * @property {object} pageTag 页面标签 *必须要
   *           {string} pageTag.type  页面标签标识类型 可选值：001：身份证, 002：案件编号,
   *                                003：车牌号,004：手机号,005：QQ, 006：微信, 007：Q群
   *           {string} pageTag.number  页面标签标识类型对应的标识号数据
   *           {string} [pageTag.carType = '小车'] 车辆页面 要传入当前车辆型号
   * @property {boolean} [showHeaderColor=false] header 是否有底色
   * @property {object} title 标题
   *           {string} title.text  标题中文
   *           {string} title.reg  说明
   * @property {string} headerImageUrl 顶部固定栏缩略图边地址
   * @property {boolean} [controlShow=true] 是否显示布控
   // * @property {boolean} [attention=false] 当前是否关注
   *
   * $emit
   * @listens
   * @property scrollBottom 页面滚动到底触发
   */
  export default {
    data() {
      return {
        loading: false,
        // 当前滚动的距离
        currentScrollTop: 0,
        // 滚动初始顶部外缘距离
        scrollMarginTop: 250,
        // 滚动初始高度
        scrollHeight: null,
        // 当前选中nav
        selectNav: -1,
        // 当前选中nav top
        selectNavTop: 0,
        // 内容数据
        list: [],
        // 当前页面关注状态
        myAttention: false,
        // 是否显示当前页面
        showPage: this.pageTag.type && this.pageTag.number
      }
    },
    props: {
      // 页面标签
      pageTag: {
        type: Object,
        default() {
          return {
            type: '',
            number: '',
            carType: '小车'
          }
        }
      },
      // header 是否有底色
      showHeaderColor: {
        type: Boolean,
        default: false
      },
      // 标题
      title: {
        type: Object,
        default() {
          return {}
        }
      },
      // 顶部固定地址
      headerImageUrl: {
        type: String,
        default: ''
      },
      // 是否显示布控 默认 true
      controlShow: {
        type: Boolean,
        default: true
      }
    },
    methods: {
      /**
       * 后退
       */
      back() {
        ANDROID.finish()
      },
      /**
       * 布控
       * @param {string} type 布控类型(01:人员;02:车辆;03;服务标示号(手机、QQ);04:其他)
       * @param {string} mark 布控标示号(如果人员,则为身份证,车辆为车辆类型+车牌号)
       */
      controlAction() {
        let type = '',
          mark = this.pageTag.number
        if (this.pageTag.type === '001') { // 人员
          type = '01'
        } else if (this.pageTag.type === '003') { // 车辆
          type = '02'
          mark = `${this.pageTag.carType}${this.pageTag.number}`
        } else if (this.pageTag.type === '004' || this.pageTag.type === '005') { // 服务标示号(手机、QQ)
          type = '03'
          mark = this.pageTag.number
        }
        if (type && mark) {
          ANDROID.AddDispatch(type, mark)
        }
      },
      /**
       * 关注
       */
      attentionAction() {
        let toast = null
        if (this.myAttention) {
          // 当前已经关注  执行取消关注操作
          request('home/left/cancelinterest', 'SC0013', {
            gzlx: this.pageTag.type,
            gzhm: [this.pageTag.number]
          }).then(r => {
            toast && toast.close()
            this.$toast({
              message: '已取消',
              duration: 2000
            })
            this.myAttention = false
          }).catch(err => {
            toast && toast.close()
            this.$toast(err.msg)
          })
        } else {
          // 当前未关注  执行关注操作
          // this.myAttention = true
          request('interest/do', 'SC0436', {
            bsh: this.pageTag.number,
            bshlx: this.pageTag.type
          }).then(r => {
            toast && toast.close()
            this.$toast({
              message: '关注成功',
              duration: 2000
            })
            this.myAttention = true
          }).catch(err => {
            toast && toast.close()
            this.$toast(err.msg)
          })
        }
      },
      /**
       * 滚到底了
       */
      loadMore() {
        this.loading = true;
        this.$emit('scrollBottom')
      },
      /**
       * 初始化滚动数据
       */
      initScroll() {
        this.$nextTick(() => {
          const layoutBodyDOM = this.$refs.layoutBody
          let blockDOM = layoutBodyDOM.children
          this.scrollHeight = layoutBodyDOM.scrollHeight
          this.list = []
          for (let i = 0; i < blockDOM.length; i++) {
            if (blockDOM[i].title) {
              this.list.push({
                text: blockDOM[i].title,
                top: blockDOM[i].offsetTop
              })
            }
          }
        })
      },
      /**
       * 获取当前类型是否关注
       */
      queryAttention() {
        request('interest/do', 'SC0438', {
          bsh: this.pageTag.number,
          bshlx: this.pageTag.type
        }).then(res => {
          if (res.flag === '1') {
            this.myAttention = true
          } else if (res.flag === '0') {
            this.myAttention = false
          }
        })
      }
    },
    watch: {
      /**
       * 内容容器高度变化 触发
       * @param val
       */
      scrollHeight(val) {
        if (val) {
          // 容器高度发生变化 重新是生成 相关滚动数据
          this.initScroll()
        } else {
          this.list = []
        }
      },
      selectNavTop(val) {
        // 根据选中目标位置  滚动
        if (val >= 0) {
          const layoutBodyDOM = this.$refs.layoutBody
          scrollTop(layoutBodyDOM, val - 100, 3)
        }
      },
      pageTag: {
        deep: true,
        handler(val) {
          this.showPage = val
        }
      },
      showPage(val) {
        if (val) {
          this.initScroll()
        }
      }
    },
    mounted() {
      // 监控 窗口滚动
      const bodyDOM = this.$refs['layoutBody']
      if (bodyDOM) {
        bodyDOM.addEventListener('scroll', (e) => {
          let headDOM = this.$refs.layout.getElementsByClassName('head-children_opacity')
          const targetDOM = e.target || e.srcElement
          this.currentScrollTop = targetDOM.scrollTop
          this.scrollHeight = bodyDOM.scrollHeight
          // 顶部栏滚动渐变效果
          if (headDOM && this.currentScrollTop > 0) {
            let opacityNumber = this.currentScrollTop / 300
            if (this.showHeaderColor) {
              opacityNumber = this.currentScrollTop / 100
            }
            opacityNumber = opacityNumber > 1 ? 1 : opacityNumber
            for (let ii = 0; ii < headDOM.length; ii++) {
              headDOM[ii].style.opacity = opacityNumber
            }
            if (!this.showHeaderColor && this.$refs.layout.getElementsByClassName('header-bg').length > 0) {
              this.$refs.layout.getElementsByClassName('header-bg')[0].style.backgroundColor = `rgba(80, 119, 170, ${opacityNumber})`
            }
          } else {
            if (!this.showHeaderColor) {
              this.$refs.layout.getElementsByClassName('header')[0].style.backgroundColor = 'rgba(80, 119, 170, 0)'
            }
          }
          // 滚动选择当前nav
          this.selectNavTop = -1
          for (let i = 0; i < this.list.length; i++) {
            if (this.currentScrollTop > this.list[i].top - this.scrollMarginTop) {
              this.selectNav = i
            } else if (this.currentScrollTop < this.list[0].top - this.scrollMarginTop) {
              this.selectNav = -1
            }
          }
        })
      }
    },
    created() {
      if (this.showPage) {
        this.initScroll()
      }
      this.queryAttention()
    }
  }
</script>
<style scoped lang="scss">
  .temp {
    margin: auto;
    width: 100%;
    max-width: 640px;
    //-webkit-overflow-scrolling: touch;
    // position:absolute; // 必须为 绝对定位
    //z-index:1;    // 必须设置 z-index  此两个 属性用于 处理 -webkit-overflow-scrolling: touch 的副作用
  }

  .top-img {
    height: 3rem;
    margin-top: .25rem;
    box-shadow: 0 0 3px rgba(0, 0, 0, 0.5);
    border-radius: .1rem;
    margin-left: -3rem;
    opacity: 0;
  }

  .header {
    text-align: center;
    height: 3.5rem;
    /*background: transparent;*/
    z-index: 9999;
    position: fixed;
    right: 0;
    left: 0;
    top: 0;
    border-bottom: 0;
    backface-visibility: hidden;
    background-color: rgba(80, 119, 170, 0);
    &-bg {
      background-color: rgba(80, 119, 170, 0);
    }
    &-solid {
      box-shadow: none;
      background-color: #5077aa;
    }
    &-children_opacity {
      opacity: 0;
    }
  }

  .title {
    color: #fff;
    padding-left: 1.5rem;
    &-tel {
      &-box {
        &:before {
          content: '';
          background-image: url('../assets/zt/tel-icon.png');
          background-size: 2rem;
          position: absolute;
          width: 2rem;
          height: 2rem;
          z-index: 100;
        }
        &_qq:before {
          background-image: url('../assets/zt/qq-icon.png');
        }
        text-indent: 2.7rem;
        margin: .75rem 0 0;
        line-height: 1.3;
        text-align: left;
        list-style-type: none;
        font-size: .6rem;
      }
      &-text {
        line-height: 1;
        font-size: 1.3rem;
        text-indent: 2.5rem;
      }
    }
  }

  .nav-bar {
    width: 100%;
    height: 2.5rem;
    overflow-y: hidden;
    position: absolute;
    background: #fff;
    left: 0;
    bottom: -2.5rem;
    border-bottom: 2px solid rgba(204, 204, 204, 0.1);
    opacity: 0;
    &-item {
      color: #333;
      padding: .6rem 0;
      &.is-selected { // nav 选中字体颜色
        color: #333;
      }
      .iconfont {
        color: #457db6;
        vertical-align: baseline;
        margin-right: -0.3rem;
        margin-bottom: .4rem;
      }
      .nav-text {
        font-size: 1.1rem;
      }
    }
  }

  .layout-body {
    height: calc(100% - 3rem);
    overflow: auto;
    &_top {
      padding-top: 4.5rem;
    }
  }

  .back-left {
    width: 2rem;
    height: 2rem;
    text-align: center;
    padding-top: .1rem !important;
    padding-left: .1rem !important;
    margin: .75rem 1.2rem auto 1rem;
    color: #FFFFFF;
    background: rgba(0, 0, 0, 0.2);
    border-radius: 50%;
    font-size: 1.5rem;
    font-weight: normal;
    font-style: normal;
    line-height: 1.4;
    display: inline-block;
    text-decoration: none;
    text-indent: -.25rem;
    -webkit-font-smoothing: antialiased;
    float: left;
  }

  footer {
    position: fixed;
    height: 3rem;
    line-height: 3rem;
    font-size: 1.2rem;
    width: 100%;
    left: 0;
    bottom: 0;
    display: flex;
    justify-content: center;
    text-align: center;
    > .button {
      flex-grow: 1;
      color: #fff;
      background: #5077aa;
      flex-basis: 0;
      &.other {
        background: #f38383;
      }
      &.cancel {
        background: #ccc;
      }
    }
  }
</style>
